package routers

import (
	"PolarDay/common/dbSource"
	"PolarDay/common/logger"
	"PolarDay/common/middleware"
	"PolarDay/models/dto"
	"PolarDay/repository"
	"PolarDay/service"
	"PolarDay/web"
	"log"

	"github.com/facebookgo/inject"
	"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
	// gin.Default 会使用Logger, Recover中间件,
	// 这里改用gin.New 新建一个没有任何默认中间件的路由
	r := gin.New()
	// 全局中间件
	// Logger 中间件将日志写入 gin.DefaultWriter，即使你将 GIN_MODE 设置为 release。
	// By default gin.DefaultWriter = os.Stdout
	r.Use(gin.Logger())
	// Recovery 中间件会 recover 任何 panic。如果有 panic 的话，会写入 500。
	r.Use(gin.Recovery())
	//gin.SetMode(setting.Config.App.RunMode)
	Configure(r)
	return r
}

func Configure(r *gin.Engine) {
	var myjwt middleware.Jwt
	var api web.SysApiWeb
	db := dbSource.Db{}
	zap := logger.Logger{}
	var injector inject.Graph
	if err := injector.Provide(
		&inject.Object{Value: &db},
		&inject.Object{Value: &zap},
		&inject.Object{Value: &myjwt},
		&inject.Object{Value: &repository.BaseRepo{}},
		&inject.Object{Value: &repository.SysApiRepo{}},
		&inject.Object{Value: &service.SysApiService{}},
		&inject.Object{Value: &repository.SysClientRepo{}},
		&inject.Object{Value: &service.SysClientService{}},
		&inject.Object{Value: &repository.SysMenuRepo{}},
		&inject.Object{Value: &service.SysMenuService{}},
		&inject.Object{Value: &repository.SysRoleRepo{}},
		&inject.Object{Value: &service.SysRoleService{}},
		&inject.Object{Value: &repository.SysUserRepo{}},
		&inject.Object{Value: &service.SysUserService{}},
		&inject.Object{Value: &api},
		&inject.Object{Value: &dto.UserPermVo{}},
	); err != nil {
		log.Fatal("inject fatal: ", err)
	}
	if err := injector.Populate(); err != nil {
		log.Fatal("injector fatal: ", err)
	}
	//zap log init
	zap.Init()
	//database connect
	if err := db.Connect(); err != nil {
		log.Fatal("db fatal:", err)
	}
	var authMiddleware = myjwt.GinJWTMiddlewareInit(middleware.Authorizator)
	//NoRoute 处理url请求 不在下面的路由就会触发这个
	r.NoRoute(authMiddleware.MiddlewareFunc(), middleware.NoRouteHandler)
	r.POST("/login", authMiddleware.LoginHandler)
	r.GET("/refresh_token", authMiddleware.RefreshHandler)
	r.Use(authMiddleware.MiddlewareFunc())

	sysApi := r.Group("/admin")
	{
		sysApi.GET("/api", api.GetApiById)
	}
}
